package com.robot.coupon.controller;

import com.robot.coupon.client.MemberClient;
import com.robot.coupon.pojo.Coupon;
import com.robot.coupon.service.CouponService;
import entity.PageResult;
import entity.Result;
import entity.StatusCode;
import io.jsonwebtoken.Claims;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * coupon控制器层
 *
 * @author wuyunbin
 */
@RestController
@CrossOrigin
@RequestMapping("/coupon")
public class CouponController {
    @Autowired
    private CouponService couponService;

    @Autowired
    private MemberClient memberClient;

    @Autowired
    private HttpServletRequest request;
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * member表status状态 0-禁用 1-启用
     */
    private String memberStatusEnable = "1";


    /**
     * 查询全部数据
     *
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public Result findAll() {
        return new Result(StatusCode.SUCCESS_QUERY, couponService.findAll());
    }

    /**
     * 根据ID查询
     *
     * @param id ID
     * @return
     */
    @RequestMapping(value = "admin/{id}", method = RequestMethod.GET)
    public Result findById(@PathVariable String id) {
        return new Result(StatusCode.SUCCESS_QUERY, couponService.findById(id));
    }


    /**
     * 分页+多条件查询
     *
     * @param searchMap 查询条件封装
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @RequestMapping(value = "/search/{page}/{size}", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap, @PathVariable int page, @PathVariable int size) {
        Page<Coupon> pageList = couponService.findSearch(searchMap, page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<Coupon>(pageList.getTotalElements(), pageList.getContent()));
    }

    /**
     * 根据条件查询
     *
     * @param searchMap
     * @return
     */
    @RequestMapping(value = "/search", method = RequestMethod.POST)
    public Result findSearch(@RequestBody Map searchMap) {
        return new Result(StatusCode.SUCCESS_QUERY, couponService.findSearch(searchMap));
    }

    /**
     * 增加
     *
     * @param coupon
     */
    @RequestMapping(method = RequestMethod.POST)
    public Result add(@RequestBody Coupon coupon) {
        couponService.add(coupon);
        return new Result(StatusCode.SUCCESS_INSERTED);
    }

    /**
     * 修改
     *
     * @param coupon
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.PUT)
    @Transactional(rollbackFor = Exception.class)
    public Result update(@RequestBody Coupon coupon, @PathVariable String id) {
        coupon.setId(id);
        couponService.update(coupon);
        return new Result(StatusCode.SUCCESS_UPDATED);
    }

    /**
     * 删除
     *
     * @param id
     */
    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    public Result delete(@PathVariable String id) {
        couponService.deleteById(id);
        return new Result(StatusCode.SUCCESS_DELETED);
    }

    /**
     * 根据会员ID查找该会员名下的所有优惠券并分页
     *
     * @param page
     * @param size
     * @return
     */
    @GetMapping("{page}/{size}")
    public Result findCouponsByMemberId(@PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Page<Coupon> pageData = couponService.findAllByMemberId(claims.getId(), page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<>(pageData.getTotalElements(), pageData.getContent()));

    }

    /**
     * 根据会员ID查找该会员名下特定状态的所有优惠券并分页
     *
     * @param status
     * @param page
     * @param size
     * @return
     */
    @GetMapping("{status}/{page}/{size}")
    public Result findCouponsByMemberIdAndStatus(@PathVariable String status, @PathVariable int page, @PathVariable int size) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Page<Coupon> pageData = couponService.findAllByMemberIdAndStatus(claims.getId(), status, page, size);
        return new Result(StatusCode.SUCCESS_QUERY, new PageResult<>(pageData.getTotalElements(), pageData.getContent()));
    }

    /**
     * 根据会员ID查找该会员名下的某张优惠券
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public Result findCouponByIdAndMemberId(@PathVariable String id) {
        Claims claims = (Claims) request.getAttribute("robot_member");
        if (claims == null) {
            return new Result(StatusCode.ERROR_TOKEN_EXPIRED);
        }
        logger.info("claims.getId()=" + claims.getId());
        //前端调用findByToken接口检查过了,所以这里不再对管理员是否存在和状态进行判断

        Coupon couponInDb = couponService.findByIdAndMemberId(id, claims.getId());
        logger.info("subOrdersInDb=" + couponInDb);
        String message = checkPojo(couponInDb);
        if (!"".equals(message)) {
            return new Result(StatusCode.ERROR, message);
        }

        return new Result(StatusCode.SUCCESS_QUERY, couponInDb);
    }

    /**
     * 检查实体类是否存在
     *
     * @param couponInDb
     * @return
     */
    public String checkPojo(Coupon couponInDb) {
        if (couponInDb == null) {
            return ("该优惠券不存在");
        }
        if (couponInDb.getDeletedAt() != null) {
            return ("该优惠券已被删除");
        }
        return "";
    }

}
